import io from "../js_sdk/socket-io/weapp.socket.io.js"
import request from "../api/request.js"
export default {
	// 连接socket.io
	conenct(context, data) {
		let {
			state
		} = context

		// 服务器地址
		// state.socket = io.connect("http://www.yemengs.cn")
		state.socket = io.connect("http://localhost:3000")
		let socket = state.socket; 

		// 登陆
		socket.emit("submit", data)

		// 接收好友请求
		socket.on("receiveDemand", data => {
			this.dispatch("getAcquire")
		})

		// 好友申请通知
		socket.on("notification", data => {
			this.dispatch("getNotice")
			this.dispatch("getFriends")
		})

		// 更新聊天记录
		socket.on("updateChat", data => {
			// 当发送信息过来的用户id和当前token用户所处的chatId相同时才更新聊天记录
			// 如果不加入这个判断，token用户所处的聊天页面将会发生用户切换的后果
			//（跳转到与发送信息过来的用户的聊天界面）
			if(data.chatType == 'private'){
				if (data.belong == state.chatId) {
					this.commit("updateChatMsg",data)
				}
			}else{
				if (data.id == state.chatId) {
					state.friend_list.map((item)=>{
						if(item.user._id.toString() == data.belong.toString()){
							data.user.name = item.nickName
						}
						return item
					})
					this.commit("updateChatMsg",data)
				}
			}
			
			this.dispatch("getDialogue")
		})

		// 群组通知
		socket.on("inform", data => {
			this.dispatch("getNotice")
			this.dispatch("getGroupList")
		})

		// 更新对话表
		socket.on("updateDialog", () => {
			this.dispatch("getDialogue")
		})

		// 更新新动态通知表
		socket.on("getDyNotify", () => {
			console.log("新动态")
			this.dispatch("getDyNotify")
		})
		
		// 获取评论通知表
		socket.on("getComNotify",()=>{
			this.dispatch("getComNotify")
		})
		
		// 有新访客
		socket.on("refreshVisitor",()=>{
			this.commit("changeVisiPage",1)
			this.dispatch("acquireVisitors")
		})
		
		// 更新留言和留言通知表
		socket.on("message",()=>{
			this.dispatch("obtainMessNotify")
			
		})
	},
	// 发送信息
	sendMsg(context, data) {
		let {
			state
		} = context
		state.socket.emit("sendMsg", data)
		if(state.chatType == 'private'){
			this.commit('updateChatMsg', { belong: state.user._id, date: new Date(), message:data.message, type: data.type });
		}else{
			this.commit('updateChatMsg', 
			{ 
				belong: state.user._id,
				user:{
					name:state.user.name,
					avatars:state.user.avatars,
					}, 
				date: new Date(), 
				message:data.message, 
				type: data.type ,
			});
		}
		
	},
	// 发送好友请求
	sendDemand(context, id) {
		let {
			state
		} = context
		state.socket.emit("sendDemand", {
			id
		})
	},
	// 处理好友请求
	dealFriend(context, data) {
		let {
			state
		} = context
		state.socket.emit("deal", data)
	},
	// 获取用户信息
	async getUserInfo(context) {
		let {
			state
		} = context
		let result = await request({
			url: '/user/info',
			data: {
				token: uni.getStorageSync('token')
			}
		});
		state.user = result[1].data.user;
	},
	// 获取通知
	async getNotice(context) {
		let {
			state
		} = context
		let res = await request({
			url: "/notify/notice",
			data: {
				token: uni.getStorageSync("token")
			}
		})
		let resData = res[1].data
		let sum = 0  //统计通知的数量
		if (resData.notify_list) {
			state.notification = resData.notify_list
			state.notification.map(item => {
				if (item.unRead == false) {
					sum++
				}
			})
			this.commit("changeNotifySum",sum)
		} else {
			state.notification = []
			this.commit("changeNotifySum",sum)
		}
	},
	// 获取聊天记录
	async getChatHistory(context, data) {
		let {
			state
		} = context
		let res = await request({
			url: "/chat/history",
			data: {
				token: uni.getStorageSync("token"),
				id: data.id,
				type: data.type,
				page:data.page,
				limit:data.limit
			}
		})
		let result = res[1].data
		let msg_list =[]
		if(data.page == 1){ //加载第一页聊天记录时的操作
			msg_list = result.chats.msg_list
		}else{ //加载更多聊天记录时的操作
			msg_list = state.chatHistory.msg_list
			msg_list.unshift(...result.chats.msg_list)
			this.commit("changeIsLoading")
		}
		let time = null     //当前信息的发送时间
		let current = null  //前一条信息的发送时间
		let distant = null  //时间差
		// 遍历更改时间，当两条信息发送的时间间隔不超过指定时间时则将时间修改为‘’
		for (var i = 0; i < msg_list.length; i++) {
			if (i == msg_list.length - 1) {
				time = new Date(msg_list[i].date).getTime()
				current = new Date().getTime()
				distant = (current - time) / 1000 / 60
			} else {
				time = new Date(msg_list[i].date).getTime()
				current = new Date(msg_list[i + 1].date).getTime()
				distant = (current - time) / 1000 / 60
			}
			distant >= 10 ? "" : msg_list[i].date = ""
		}
		result.chats.msg_list = msg_list
		this.commit("changeChatHistory",result.chats)
		if(state.chatType=="private"){
			this.commit("changeChatName",result.name)
		}
		state.chatCount = result.count
	},
	// 获取聊天列表
	async getDialogue(context) {
		let {
			state
		} = context
		let res = await request({
			url: "/dialogue/list",
			data: {
				token: uni.getStorageSync("token"),
			}
		})
		state.dialogueList = res[1].data
		// 统计所有新信息的数量
		let sum = 0
		for(let i= 0;i<state.dialogueList.length;i++){
			let item = state.dialogueList[i]
			if(item.id == state.chatId){// 当天聊天页面的新信息的数量
				state.newMsgCount = item.unRead
			}
			sum = sum + item.unRead
		}
		this.commit("changeDialogueUnRead",sum)
	},
	// 获取好友请求数量
	async getAcquire(context) {
		let {
			state
		} = context
		let res = await request({
			url: '/friend/acquire',
			data: {
				token: uni.getStorageSync('token'),
				type: 'number'
			}
		});
		this.commit("changeAcquire",res[1].data.applyList.length)
	},
	// 获取好友列表
	async getFriends(context) {
		let {
			state
		} = context
		let res = await request({
			url: '/friend/friends',
			data: {
				token: uni.getStorageSync('token')
			}
		});
		let result = res[1].data;
		state.friends = result.friends;
		state.friend_list = result.friend_list
		state.total = result.total;
	},
	// 获取群组列表
	async getGroupList(context) {
		let {
			state
		} = context
		let res = await request({
			url: '/group/list',
			data: {
				token: uni.getStorageSync('token')
			}
		})
		state.groupList = res[1].data
	},
	// 获取群详情
	async getInfo(context, id) {
		let {
			state
		} = context
		let res = await request({
			url: '/group/info',
			data: {
				id,
				token: uni.getStorageSync('token')
			}
		});
		this.commit("changeGroupInfo",res[1].data)
		// state.groupInfo = res[1].data.group;
		// this.commit("changeChatName",res[1].data.group.name)
		// state.g_nickName = res[1].data.nickName;
	},
	// 获取新动态通知表
	async getDyNotify(context){
		let {
			state
		} = context
		let res = await request({
			url: '/dynamic/notify/get',
			data: {
				token: uni.getStorageSync('token')
			}
		});
		this.commit("changeDyNotify",res[1].data)
	},
	// 获取评论通知
	async getComNotify(context){
		let {
			state
		} = context
		state.count = 0
		let res = await request({
			url:"/comment/notify",
			data:{
				token: uni.getStorageSync('token'),
			}
		})
		this.commit("changeComNotify",res[1].data)
	},
	// 记录访客
	async recordVisitor(context,id){
		let {
			state
		} = context
		let res = await request({
			url:"/visitor/record",
			data:{
				id,
				token:uni.getStorageSync("token")
			},
			method:"POST"
		})
	},
	// 获取访客
	async acquireVisitors(context){
		let {
			state
		} = context
		if(state.visi_page==1){ //重置visitors
			this.commit("changeVisitors",[])
		}
		let res = await request({
			url:"/visitor/acquire",
			data:{
				token:uni.getStorageSync("token"),
				page:state.visi_page++,
				limit:state.visi_limit
			}
		})
		res = res[1].data
		state.visi_count = res.count
		state.visitors.push(...res.visitors) 
		this.commit("changeNewVisitorSum",res.newVisitor)
	},
	// 更新新访客数量
	async updateVisitor(context){
		let res = await request({
			url:"/visitor/update",
			data:{
				token:uni.getStorageSync("token"),
			},
			method:"POST"
		})
		this.dispatch("acquireVisitors")
	},
	// 获取留言通知表
	async obtainMessNotify(context){
		let {state} = context
		let res = await request({
			url:"/message/notify/obtain",
			data:{
				token:uni.getStorageSync("token"),
			}
		})
		state.messNotify = res[1].data.messNotify
		this.commit("changeMessageSum",res[1].data.count)
	},
	// 更新未读留言通知表
	async updateMessNotify(context){
		let {state} = context
		let res = await request({
			url:"/message/notify/update",
			data:{
				token:uni.getStorageSync("token"),
			},
			method:"POST"
		}) 
		if(res[1].data.status){
			this.dispatch("obtainMessNotify")
		}
	}
}
